package com.lvyh.lightframe.log.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.UUID;


/**
 * @author lvyh 2021/03/20.
 */
@Aspect
@Component
@Order(0)
@Slf4j
public class RestControllerLogTraceAspect {

    private final String traceId = "traceId";

    @Around("within(@org.springframework.web.bind.annotation.RestController *)")
    public Object initLogTraceController(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("log traceId create success.");
        MDC.put(this.traceId, UUID.randomUUID().toString().replace("-", "").toLowerCase());
        Object object = null;
        try {
            object = joinPoint.proceed();
            return object;
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.info("log traceId remove success.");
            MDC.clear();
        }
    }

}
